package me.shurufa.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.CommentDetailActivity;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.activities.NewUserCenterActivity;
import me.shurufa.activities.ShareEditActivity;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.holder.BaseViewHolder;
import me.shurufa.bean.BookComment;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;
import me.shurufa.widget.animutils.AnimOnTouchListener;

/**
 * 作者 : andy
 * 日期 : 16/3/8 14:50
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书评列表适配器
 */
public class BookCommentNewAdapter extends RecyclerView.Adapter<BookCommentNewAdapter.BookCommentHolder> {
    private List<BookComment> mDatas;
    private Context mContext;
    private OnSocialBarClickListener mOnOperateClickListener; // 点击监听器回调

    private String mBookname;
    private int mWhereFrom;
    private SparseBooleanArray mCommentExpandState = new SparseBooleanArray(); // 评论展开的状态  默认false

    public BookCommentNewAdapter(Context context, String bookname, List<BookComment> datas, int whereFrom) {
        this.mDatas = datas;
        this.mContext = context;
        this.mWhereFrom = whereFrom;
        this.mBookname = bookname;
    }

    @Override
    public BookCommentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_bookdetail_comment, parent, false);
        return new BookCommentHolder(v);
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    @Override
    public void onBindViewHolder(final BookCommentHolder holder, final int position) {
        try {
            bindData(holder, position);
            bindListener(holder, position);
        } catch (Exception e) {
            e.printStackTrace();
            Utils.showToast(R.string.sys_err);
        }
    }

    private void bindData(BookCommentHolder holder, int position) {
        BookComment bookComment = mDatas.get(position);
        holder.tv_comment_content.setText(bookComment.content);
        holder.tv_info_user.setText(bookComment.user_info.username);
        holder.tv_info_time.setText(Utils.getFormatTime(bookComment.created_at));

        boolean isZero = bookComment.zan_num == 0;
        try {
            int praiseNum = bookComment.zan_num;
            if (praiseNum <= 0) {
                isZero = true;
            }
        } catch (NumberFormatException e) {
        }
        holder.tv_praise_num.setText(isZero ? null : bookComment.zan_num + "");
        holder.tv_comment_num.setText(bookComment.comment_num == 0 ? null : (bookComment.comment_num + ""));

        boolean favorite = bookComment.is_fav == 1;
        boolean praise = bookComment.is_zan == 1;
        holder.tv_praise.setBackgroundResource(praise ? R.drawable.ic_praise_selected : R.drawable.ic_praise_normal);
        holder.tv_collect.setBackgroundResource(favorite ? R.drawable.ic_collect_selected : R.drawable.ic_collect_normal);

        // 若是从消息中心跳进来的，不显示四个操作按钮，并且默认展开评论列表且不可收起
        if (Constants.TYPE_FROM_NOTICE_MESSAGE_BOOKCOMMENT == mWhereFrom) {
            // 不显示四个操作按钮
            holder.layout_social_bar.setVisibility(View.GONE);
            // 默认展开评论列表
            mCommentExpandState.put(position, true);
            holder.ll_collapse.setVisibility(View.GONE);
            holder.expand_comment_layout.setVisibility(mCommentExpandState.get(position) ? View.VISIBLE : View.GONE);
        }

    }


    private void bindListener(final BookCommentHolder holder, final int position) {
        final BookComment bookComment = mDatas.get(position);

        // 点击昵称
        if (Constants.FROM_USER_CENTER != mWhereFrom) {
            holder.tv_info_user.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent in = new Intent(mContext, NewUserCenterActivity.class);
                    NewUserCenterActivity.initArguments(in, bookComment.user_info, false);
                    mContext.startActivity(in);
                }
            });
        }
        holder.btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(mContext, ShareEditActivity.class);
                ShareEditActivity.initArguments(in, mBookname, null, bookComment);
                mContext.startActivity(in);
            }
        });

        // 赞
        holder.btn_praise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!handleLoginClick()) {
                    return;
                }
                if (mOnOperateClickListener != null) {
                    mOnOperateClickListener.onPraiseClick(bookComment.is_zan == 1, bookComment);
                }
            }
        });

        // 收藏
        holder.btn_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!handleLoginClick()) {
                    return;
                }
                if (mOnOperateClickListener != null) {
                    mOnOperateClickListener.onCollectClick(bookComment.is_fav == 1, bookComment);
                }
            }
        });

        // 点击评论
        holder.btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!handleLoginClick()) {
                    return;
                }

                Intent in = new Intent(mContext, CommentDetailActivity.class);
                CommentDetailActivity.initArguments(in, mBookname, bookComment.id, Constants.TYPE_COMMENT_BOOK_COMMENT);
                mContext.startActivity(in);

            }
        });


        // 点击评论底部的收回按钮 收缩评论内容
        holder.ll_collapse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.expand_comment_layout.setVisibility(View.GONE);
                mCommentExpandState.put(position, false);
            }
        });

    }

    public class BookCommentHolder extends BaseViewHolder {
        @Bind(R.id.tv_comment_content)
        TextView tv_comment_content;
        @Bind(R.id.tv_info_user)
        TextView tv_info_user;
        @Bind(R.id.tv_info_time)
        TextView tv_info_time;

        @Bind(R.id.layout_social_bar)
        LinearLayout layout_social_bar;

        @Bind(R.id.ll_praise)
        LinearLayout btn_praise;
        @Bind(R.id.ll_collect)
        LinearLayout btn_collect;
        @Bind(R.id.tv_praise_num)
        TextView tv_praise_num;
        @Bind(R.id.tv_comment_num)
        TextView tv_comment_num;

        @Bind(R.id.tv_praise)
        TextView tv_praise;
        @Bind(R.id.tv_collect)
        TextView tv_collect;

        @Bind(R.id.ll_share)
        LinearLayout btn_share;
        @Bind(R.id.ll_comment)
        LinearLayout btn_comment;

        @Bind(R.id.ll_collapse)
        LinearLayout ll_collapse;
        @Bind(R.id.expand_comment_layout)
        LinearLayout expand_comment_layout;

        @Bind(R.id.comment_container)
        LinearLayout comment_container;

        public BookCommentHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    @Deprecated
    public void append(BookComment[] items) {
        int pos = mDatas.size();
        for (BookComment item : items) {
            if (!mDatas.contains(item))
                mDatas.add(item);
        }
        notifyItemRangeInserted(pos, items.length);
    }

    public void append(List<BookComment> items) {
        if (Utils.isNullForList(items)) {
            return;
        }
        int pos = mDatas.size();
        for (BookComment item : items) {
            if (!mDatas.contains(item)) {
                mDatas.add(item);
            }
        }
        notifyItemRangeInserted(pos, items.size());
    }

    public void clear() {
        int size = mDatas.size();
        mDatas.clear();
        this.notifyItemRangeRemoved(0, size);
    }

    public void setOnSocialBarClickListener(OnSocialBarClickListener l) {
        this.mOnOperateClickListener = l;
    }

    /**
     * 评论按钮点击接口
     */
    public interface OnSocialBarClickListener {
        /**
         * 点击点赞按钮
         * @param prePraise
         * @param comment     true: 点赞   false: 取消点赞
         */
        void onPraiseClick(boolean prePraise, BookComment comment);

        /**
         * 点击收藏按钮
         * @param preCollect true: 收藏   false: 取消收藏
         * @param comment
         */
        void onCollectClick(boolean preCollect, BookComment comment);
    }

    private boolean handleLoginClick() {
        boolean isLogin = PersistenceUtils.isLogin();
        Intent in = null;
        // 已登录 跳转到ProfileActivity
        if (isLogin) {
            return true;
        }

        // 未登录 则跳转至登录界面，点击登录时需要返回到当前界面
        else {
            in = new Intent(mContext, NewLoginActivity.class);
            in.setAction(Constants.ACTION_GO_LOGIN);
            EventBus.getDefault().postSticky(in);
            //mContext.startActivity(in);
            return false;
        }
    }

}
